package com.xo.xodemo.controller.qrcode;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.xo.xodemo.common.Result;
import com.xo.xodemo.mapper.db2.AdminUserMapper;
import com.xo.xodemo.mapper.db2.OrderMapper;

import com.xo.xodemo.model.Order;
import com.xo.xodemo.service.JHService;
import org.apache.commons.lang.RandomStringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/QrCode")
public class QrCodeController {
    @Autowired
    private JHService jhService;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    //二维码生成接口
    @RequestMapping ( value = "/build" )
    public String build(@RequestParam("userId") String userId, @RequestParam("buyType") String buyType,Model model) throws IOException {
        //尊享 用户等级为3
        String userlevel=adminUserMapper.selectUserLevelbyUserid(userId);
        if("3".equals(userlevel) && !"1".equals(buyType)){
            model.addAttribute("content","参数错误");
            return "goods/goodsqr";
        }
        else {
            String orderId= getOrderId(userId);
            String price=orderMapper.getprice(buyType);
            Order order=new Order();
            order.setOrderId(orderId);
            order.setType(buyType);
            order.setPayment(price);
            order.setUserId(userId);
            stringRedisTemplate.boundValueOps(orderId).set(JSON.toJSONString(order),30 ,TimeUnit.MINUTES);
            String s=jhService.createQrCode(userId,price,orderId,buyType);
            model.addAttribute("content",s);
            return "goods/goodsqr";
        }
    }
    //二维码生成接口
    @RequestMapping ( value = "/buildnew" )
    public String buildnew(@RequestParam("userId") String userId, @RequestParam("buyType") String buyType,Model model) throws IOException {
        String userlevel=adminUserMapper.selectUserLevelbyUserid(userId);
        //如果用户id是已经购买了正式版本（标准以上版本）则不允许购买
        if(!"0".equals(userlevel)&&!"1".equals(userlevel)&&!"4".equals(userlevel)){
            model.addAttribute("content","请不要重复购买");
            return "goods/goodsqr";
        }
        if("4".equals(userlevel)&&"3".equals(buyType)){
            model.addAttribute("content","请不要重复购买");
            return "goods/goodsqr";
        }
        else {
            String orderId= getOrderId(userId);
            String price=orderMapper.getprice(buyType);
            if(price==null){
                model.addAttribute("content","不存在此商品");
                return "goods/goodsqr";
            }
            Order order=new Order();
            order.setOrderId(orderId);
            order.setType(buyType);
            order.setPayment(price);
            order.setUserId(userId);
            stringRedisTemplate.boundValueOps(orderId).set(JSON.toJSONString(order),30 ,TimeUnit.MINUTES);
            String s=jhService.createQrCode(userId,price,orderId,buyType);
            model.addAttribute("content",s);
            return "goods/goodsqr";
        }
    }
    //查询支付状态
    @RequestMapping ( value = "/getpaystatus" )
    @ResponseBody
//    @CrossOrigin
    public Result getpaystatus(@RequestParam("orderId") String orderId, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
       Order order=orderMapper.getorder(orderId);
       if(order!=null){
           return Result.success(order.getSuccess());
       }
       else {
           return Result.error();
       }

    }
//    生成25位订单id
        private  synchronized  String getOrderId(String userId) {
        //时间（精确到毫秒）
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        //3位随机数
        String randomNumeric = RandomStringUtils.randomNumeric(3);
        //用户id长度设置为5
        int subStrLength = 5;
        int length = userId.length();
        String str;
        if (length >= subStrLength) {
            str = userId.substring(length - subStrLength, length);
        } else {
            str = String.format("%0" + subStrLength + "d", Integer.valueOf(userId));
        }
        String orderNum = localDate + randomNumeric + str;
        return orderNum;
    }


}

